package de.hsowl.tod4a.global.xml;

import java.io.File;
import java.io.IOException;
import java.io.StringReader;

import org.apache.log4j.Logger;
import org.jdom.Document;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

import de.hsowl.tod4a.server.FileWatcher;

public class SAXBuilderHelper extends SAXBuilder {

	private static Logger logger = Logger.getLogger(SAXBuilderHelper.class);


	public SAXBuilderHelper(boolean validate) {
		super(validate);
	}

	public Document build_(File f) throws Exception {
		Exception e = null;
		Document doc = null;
		try {
			while (FileWatcher.accessFile(f) == false) {
				try {
					// warten bis file offen
					Thread.sleep(10);
				} catch (Exception ex) {
					logger.error("", ex);
				}
			}

			doc = super.build(f);
		} catch (Exception ex) {
			logger.error("XML-Error", ex);
			e = ex;
		}
		FileWatcher.releaseFile(f);

		if (e != null) {
			throw e;
		}
		return doc;
	}

	@Override
	public Document build(File file) throws JDOMException, IOException {
		try {
			return build_(file);
		} catch (Exception e) {
			if (e instanceof JDOMException) {
				throw (JDOMException) e;
			} else if (e instanceof IOException) {
				throw (IOException) e;
			}
		}
		return null;
	}

	public Document build(String xml) throws JDOMException, IOException {
		return this.build(new StringReader(xml));
	}

}
